import React from 'react';
import {connect} from 'dva';
import {Card, Form, Input, Icon, Tooltip, Button, Upload, Modal, Row, Col} from 'antd';
import ContentWrapper from '../layouts/ContentWrapper';
import {beforeUpload} from "../../utils/utils";
import {qiniuConfig} from '../../config/config';

const FormItem = Form.Item;

@connect(state => ({
  loading: state.loading,
  customer: state.customer,
}))
@Form.create()
export default class CustomerCU extends React.PureComponent {

  constructor(props) {
    super(props);

    const {match: {params}} = this.props;
    this.state = {
      opType: params.id ? 'edit' : 'new',
      fileList: [],
      previewVisiable: false,
      previewImage: '',
    };
  }

  componentDidMount() {
    const {dispatch, match: {params}} = this.props;
    if (params.id) {
      dispatch({
        type: 'customer/get',
        payload: params.id,
      });
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const currentMatchedId = this.props.match.params.id;
    const nextMatchedId = nextProps.match.params.id;
    if (nextMatchedId && currentMatchedId !== nextMatchedId) {
      this.props.dispatch({
        type: 'customer/get',
        payload: nextMatchedId
      });
    }

    // TODO optimize (add compare between old and new props)
    if (this.state.fileList.length === 0 && nextProps.customer.item && nextProps.customer.item.avatar) {
      const fileList = [{
        uid: -1,
        name: 'xxx.png',
        status: 'done',
        url: nextProps.customer.item.avatar,
      }];
      this.setState({fileList});
    }
  }

  componentWillUnmount() {
    this.props.dispatch({
      type: 'customer/cleanItem',
    });
  }

  handleUploadChange = ({file, fileList}) => {
    const {status, response = {}} = file;
    if (status === 'done') {
      this.props.form.setFieldsValue({
        avatar: qiniuConfig.baseExternalLink + (response.hash || ''),
      });
    } else if (status === 'removed') {
      this.props.form.setFieldsValue({
        avatar: '',
      });
    }
    this.setState({fileList});
  };

  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  handleClosePreviewModal = () => this.setState({previewVisible: false});

  handleSubmit = (e) => {
    e.preventDefault();
    const {dispatch, form: {validateFieldsAndScroll}} = this.props;
    const {opType} = this.state;

    validateFieldsAndScroll((errors, values) => {
      if (errors) {
        return;
      }

      const data = {
        ...values,
      };

      if (opType === 'new') {
        dispatch({
          type: `customer/create`,
          payload: data,
        });
      } else {
        const {customer: {item}} = this.props;
        dispatch({
          type: `customer/update`,
          payload: {
            id: item.id,
            data
          },
        });
      }
    });
  };

  render() {
    const {history, loading, form: {getFieldDecorator}, customer: {item}} = this.props;
    const {opType, previewVisible, previewImage, fileList} = this.state;
    const itemLoading = loading.effects['customer/get'];
    const formLoading = opType === 'new' ? loading.effects['customer/create'] : loading.effects['customer/update'];

    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 4},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 20},
      },
    };

    const tailFormItemLayout = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 22, offset: 2},
      },
    };

    return (
      <ContentWrapper loading={itemLoading}>
        <Card
          title={opType === 'new' ? '新增会员' : '编辑会员'}
          bordered={false}
        >
          <Form>
            <Row gutter={16}>
              <Col span={12}>
                {getFieldDecorator('avatar', {
                  initialValue: item.avatar,
                })(
                  <Input type="hidden"/>
                )}
                {/*<FormItem
                  {...formItemLayout}
                  hasFeedback
                  label={(
                    <span>
                      用户名&nbsp;
                      <Tooltip title="唯一，用于登录系统，设置后不可更改">
                        <Icon type="question-circle-o"/>
                      </Tooltip>
                    </span>
                  )}
                >
                  {getFieldDecorator('username', {
                    initialValue: item.username,
                    rules: [{
                      required: true,
                      message: '请输入用户名！',
                    }],
                  })(
                    <Input disabled={opType === 'new' ? false : true}/>
                  )}
                </FormItem>*/}
                <FormItem
                  {...formItemLayout}
                  hasFeedback
                  label="姓名"
                >
                  {getFieldDecorator('name', {
                    initialValue: item.name,
                    rules: [{
                      required: true,
                      message: '请输入姓名！',
                    }],
                  })(
                    <Input/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  hasFeedback
                  label={(
                    <span>
                      手机&nbsp;
                      <Tooltip title="唯一，用于登录系统，设置后不可更改">
                        <Icon type="question-circle-o"/>
                      </Tooltip>
                    </span>
                  )}
                >
                  {getFieldDecorator('phone', {
                    initialValue: item.phone,
                    rules: [{
                      required: true,
                      message: '请输入手机号码！',
                    }, {
                      pattern: /^1[34578]\d{9}$/,
                      message: '手机号码格式不正确！',
                    }],
                  })(
                    <Input disabled={opType === 'new' ? false : true}/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  hasFeedback
                  label="邮箱"
                >
                  {getFieldDecorator('email', {
                    initialValue: item.email,
                    rules: [{
                      type: 'email',
                      message: '邮箱格式不正确！',
                    }],
                  })(
                    <Input/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  hasFeedback
                  label="公司"
                >
                  {getFieldDecorator('company', {
                    initialValue: item.company,
                    rules: [{
                      required: true,
                      message: '请输入公司！',
                    }],
                  })(
                    <Input/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  hasFeedback
                  label="职位"
                >
                  {getFieldDecorator('position', {
                    initialValue: item.position,
                    rules: [{
                      required: true,
                      message: '请输入职位！',
                    }],
                  })(
                    <Input/>
                  )}
                </FormItem>
              </Col>
              <Col span={12}>
                <Upload
                  name="file"
                  listType="picture-card"
                  className="avatar-uploader"
                  action={`${qiniuConfig.server}`}
                  data={{token: qiniuConfig.token}}
                  fileList={fileList}
                  beforeUpload={beforeUpload}
                  onChange={this.handleUploadChange}
                  onPreview={this.handlePreview}
                >
                  {fileList.length >= 1
                    ? null
                    : <div>
                      <Icon type="plus"/>
                      <div className="ant-upload-text">Upload</div>
                    </div>
                  }
                </Upload>
              </Col>
              <Col span={24}>
                <FormItem {...tailFormItemLayout}>
                  <Button onClick={() => history.goBack()}>取消</Button>
                  <Button style={{marginLeft: 8}} type="primary" onClick={this.handleSubmit}
                          loading={formLoading}>提交</Button>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Card>
        <Modal
          visible={previewVisible}
          footer={null}
          onCancel={this.handleClosePreviewModal}
        >
          <img style={{width: '100%'}} src={previewImage}  alt="example"/>
        </Modal>
      </ContentWrapper>
    );
  }
}

/*
TODO move to less
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
*/
